package teamdao

import (
	"itodo/core/dao/table"
	"itodo/core/localwrap"
	"itodo/core/service/common"

	"github.com/RocksonZeta/wrap/redised"
	"github.com/RocksonZeta/wrap/utils/sutil"
	"github.com/RocksonZeta/wrap/utils/timeutil"
)

const tableTask = "Task"
const tableTaskId = "Id"

var logTasks = localwrap.GetLogger().Fork("itodo/core/dao/teamdao", "Tasks")

//Tasks 
type Tasks struct {
	*redised.RedisedMysql
}

type TasksQueryParam struct {
	common.Page
	Name string
}

//Query 根据条件查询
func (s Tasks) Query(param TasksQueryParam) ([]table.Task, int64) {
	logTasks.Debug().Func("Query").Interface("param", param).Send()
	wsql := " from Task where 1=1"
	if param.Name != "" {
		param.Name = "%" + param.Name + "%"
		wsql += " and name like :Name"
	}
	ssql := "select *" + wsql + " order by ct desc" + param.Limit()
	csql := "select count(*)" + wsql
	var r []table.Task
	s.Mysql.Select(&r, ssql, param)
	return r, s.Mysql.SelectInt(csql, param)
}

func (s Tasks) Get(id int) table.Task {
	logTasks.Debug().Func("Get").Int("id", id).Send()
	var r table.Task
	s.RedisedMysql.Get(&r, tableTask, tableTaskId, id)
	return r
}

func (s Tasks) List(ids []int) []table.Task {
	logTasks.Debug().Func("List").Ints("ids", ids).Send()
	var r []table.Task
	s.RedisedMysql.List(&r, tableTask, tableTaskId, ids)
	return r
}
func (s Tasks) ListAsMap(ids []int) map[int]table.Task {
	logTasks.Debug().Func("ListAsMap").Ints("ids", ids).Send()
	l := s.List(ids)
	r := make(map[int]table.Task, len(l))
	for _, v := range l {
		r[v.Id] = v
	}
	return r
}

func (s Tasks) Delete(id int) {
	logTasks.Debug().Func("Delete").Int("id", id).Send()
	old := s.Get(id)
	s.Mysql.Delete(tableTask, tableTaskId, id)
	s.ClearCache(old)
}

func (s Tasks) ClearCache(old table.Task) {
	logTasks.Debug().Func("ClearCache").Int("id", old.Id).Send()
	s.Redis.Del(s.KeyFn(tableTask, old.Id))
}
type TasksUpdateParam struct {
	Id int
	Name string
	TeamId int
	Uid int
	State int
	Day int
	StartTime int
	Duration int
}

func (s Tasks) Update(param TasksUpdateParam) {
	logTasks.Debug().Func("Update").Interface("param", param).Send()
	s.Mysql.Patch(tableTask, tableTaskId, param)
	s.Redis.Del(s.KeyFn(tableTask, param.Id))
	// s.ClearCache(s.Get(param.Id)) if no index updated
}

type TasksAddParam struct {
	Name string
	TeamId int
	Uid int
	State int
	Day int
	StartTime int
	Duration int
}

func (s Tasks) Add(param TasksAddParam) table.Task {
	logTasks.Debug().Func("Add").Interface("param", param).Send()
	var t table.Task
	sutil.Copy(param, &t)
	t.Ct = timeutil.Now()
	s.Mysql.AddTable(t)
	s.Mysql.Insert(&t)
	s.ClearCache(t)
	return t
}
